<?php
/**
 * 导入API - 支持从多种格式导入书签
 */

require_once 'BaseAPI.php';

class ImportAPI extends BaseAPI {
    
    public function handleRequest() {
        $method = $_SERVER['REQUEST_METHOD'];
        $action = $_GET['action'] ?? '';
        
        switch($action) {
            case 'parse':
                if ($method === 'POST') {
                    $this->parseFile();
                }
                break;
            case 'import':
                if ($method === 'POST') {
                    $this->importBookmarks();
                }
                break;
            case 'analyze':
                if ($method === 'POST') {
                    $this->analyzeFile();
                }
                break;
            default:
                sendErrorResponse('无效的操作', 400);
        }
    }
    
    /**
     * 解析上传的文件
     */
    private function parseFile() {
        $user = $this->requireAuth();
        
        if (!isset($_FILES['file'])) {
            sendErrorResponse('请选择要导入的文件');
        }
        
        $file = $_FILES['file'];
        
        if ($file['error'] !== UPLOAD_ERR_OK) {
            sendErrorResponse('文件上传失败');
        }
        
        // 检查文件大小（最大10MB）
        if ($file['size'] > 10 * 1024 * 1024) {
            sendErrorResponse('文件大小不能超过10MB');
        }
        
        $fileContent = file_get_contents($file['tmp_name']);
        $fileName = $file['name'];
        $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        
        // 根据文件类型解析
        $bookmarks = [];
        switch($fileExt) {
            case 'html':
            case 'htm':
                $bookmarks = $this->parseHTMLBookmarks($fileContent);
                break;
            case 'json':
                $bookmarks = $this->parseJSONBookmarks($fileContent);
                break;
            case 'csv':
                $bookmarks = $this->parseCSVBookmarks($fileContent);
                break;
            default:
                sendErrorResponse('不支持的文件格式，请上传 HTML、JSON 或 CSV 文件');
        }
        
        if (empty($bookmarks)) {
            sendErrorResponse('文件中没有找到有效的书签数据');
        }
        
        // 检查重复
        $existingUrls = $this->getUserBookmarkUrls($user['id']);
        foreach ($bookmarks as &$bookmark) {
            $bookmark['is_duplicate'] = in_array($bookmark['url'], $existingUrls);
        }
        
        sendSuccessResponse([
            'bookmarks' => $bookmarks,
            'total' => count($bookmarks),
            'duplicates' => count(array_filter($bookmarks, fn($b) => $b['is_duplicate'])),
            'new' => count(array_filter($bookmarks, fn($b) => !$b['is_duplicate']))
        ], '解析成功');
    }
    
    /**
     * 解析HTML书签文件（Netscape格式）
     */
    private function parseHTMLBookmarks($html) {
        $bookmarks = [];
        
        // 使用DOMDocument解析HTML
        libxml_use_internal_errors(true);
        $dom = new DOMDocument();
        $dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
        libxml_clear_errors();
        
        $xpath = new DOMXPath($dom);
        $links = $xpath->query('//a[@href]');
        
        $currentFolder = '未分组';
        
        foreach ($links as $link) {
            $url = $link->getAttribute('href');
            $name = trim($link->textContent);
            
            if (empty($url) || empty($name)) {
                continue;
            }
            
            // 跳过javascript和data链接
            if (preg_match('/^(javascript:|data:|about:)/i', $url)) {
                continue;
            }
            
            // 尝试获取父级H3作为文件夹名
            $parent = $link->parentNode;
            while ($parent) {
                if ($parent->nodeName === 'dl') {
                    $h3 = $xpath->query('.//preceding-sibling::h3[1]', $parent);
                    if ($h3->length > 0) {
                        $currentFolder = trim($h3->item(0)->textContent);
                    }
                    break;
                }
                $parent = $parent->parentNode;
            }
            
            // 获取添加时间
            $addDate = $link->getAttribute('add_date');
            $createdAt = $addDate ? date('Y-m-d H:i:s', $addDate) : null;
            
            $bookmarks[] = [
                'name' => $name,
                'url' => $url,
                'description' => '',
                'folder' => $currentFolder,
                'created_at' => $createdAt
            ];
        }
        
        return $bookmarks;
    }
    
    /**
     * 解析JSON书签文件
     */
    private function parseJSONBookmarks($json) {
        $data = json_decode($json, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            sendErrorResponse('JSON格式错误：' . json_last_error_msg());
        }
        
        $bookmarks = [];
        
        // 支持我们自己的导出格式
        if (isset($data['bookmarks']) && is_array($data['bookmarks'])) {
            foreach ($data['bookmarks'] as $item) {
                $bookmarks[] = [
                    'name' => $item['name'] ?? '',
                    'url' => $item['url'] ?? '',
                    'description' => $item['description'] ?? '',
                    'folder' => $item['category_name'] ?? '未分组',
                    'created_at' => $item['created_at'] ?? null
                ];
            }
        }
        // 支持简单的JSON数组格式
        elseif (is_array($data)) {
            foreach ($data as $item) {
                if (isset($item['url'])) {
                    $bookmarks[] = [
                        'name' => $item['name'] ?? $item['title'] ?? '',
                        'url' => $item['url'] ?? '',
                        'description' => $item['description'] ?? $item['desc'] ?? '',
                        'folder' => $item['folder'] ?? $item['category'] ?? '未分组',
                        'created_at' => $item['created_at'] ?? null
                    ];
                }
            }
        }
        
        return $bookmarks;
    }
    
    /**
     * 解析CSV书签文件
     */
    private function parseCSVBookmarks($csv) {
        $bookmarks = [];
        $lines = str_getcsv($csv, "\n");
        
        if (empty($lines)) {
            return $bookmarks;
        }
        
        // 检测CSV是否有BOM
        $lines[0] = preg_replace('/^\x{FEFF}/u', '', $lines[0]);
        
        // 第一行作为表头
        $header = str_getcsv($lines[0]);
        
        // 标准化表头（支持中英文）
        $headerMap = [];
        foreach ($header as $index => $col) {
            $col = strtolower(trim($col));
            if (in_array($col, ['name', '名称', 'title', '标题'])) {
                $headerMap['name'] = $index;
            } elseif (in_array($col, ['url', '网址', 'link', '链接', 'address'])) {
                $headerMap['url'] = $index;
            } elseif (in_array($col, ['description', '描述', 'desc', '备注', 'note'])) {
                $headerMap['description'] = $index;
            } elseif (in_array($col, ['folder', '文件夹', 'category', '分组', 'group'])) {
                $headerMap['folder'] = $index;
            }
        }
        
        // 解析数据行
        for ($i = 1; $i < count($lines); $i++) {
            $row = str_getcsv($lines[$i]);
            
            if (empty($row) || count($row) < 2) {
                continue;
            }
            
            $bookmark = [
                'name' => isset($headerMap['name']) ? ($row[$headerMap['name']] ?? '') : ($row[0] ?? ''),
                'url' => isset($headerMap['url']) ? ($row[$headerMap['url']] ?? '') : ($row[1] ?? ''),
                'description' => isset($headerMap['description']) ? ($row[$headerMap['description']] ?? '') : '',
                'folder' => isset($headerMap['folder']) ? ($row[$headerMap['folder']] ?? '未分组') : '未分组',
                'created_at' => null
            ];
            
            if (!empty($bookmark['url'])) {
                $bookmarks[] = $bookmark;
            }
        }
        
        return $bookmarks;
    }
    
    /**
     * 执行导入
     */
    private function importBookmarks() {
        $user = $this->requireAuth();
        $data = getRequestData();
        
        if (!isset($data['bookmarks']) || !is_array($data['bookmarks'])) {
            sendErrorResponse('缺少书签数据');
        }
        
        $bookmarks = $data['bookmarks'];
        $targetCategoryId = $data['category_id'] ?? null;
        $skipDuplicates = $data['skip_duplicates'] ?? true;
        
        // 获取用户现有URL
        $existingUrls = $this->getUserBookmarkUrls($user['id']);
        
        // 如果指定了分组，验证分组是否存在
        if ($targetCategoryId) {
            $stmt = $this->db->prepare("SELECT id FROM categories WHERE id = ? AND user_id = ?");
            $stmt->execute([$targetCategoryId, $user['id']]);
            if (!$stmt->fetch()) {
                sendErrorResponse('指定的分组不存在');
            }
        }
        
        $imported = 0;
        $skipped = 0;
        $failed = 0;
        $folderMap = []; // 文件夹名到分组ID的映射
        
        foreach ($bookmarks as $bookmark) {
            // 跳过重复
            if ($skipDuplicates && in_array($bookmark['url'], $existingUrls)) {
                $skipped++;
                continue;
            }
            
            // 确定分组ID
            $categoryId = $targetCategoryId;
            
            // 如果没有指定目标分组，尝试根据文件夹名匹配或创建分组
            if (!$categoryId && !empty($bookmark['folder']) && $bookmark['folder'] !== '未分组') {
                if (!isset($folderMap[$bookmark['folder']])) {
                    // 查找同名分组
                    $stmt = $this->db->prepare("SELECT id FROM categories WHERE user_id = ? AND name = ?");
                    $stmt->execute([$user['id'], $bookmark['folder']]);
                    $existingCategory = $stmt->fetch();
                    
                    if ($existingCategory) {
                        $folderMap[$bookmark['folder']] = $existingCategory['id'];
                    } else {
                        // 创建新分组
                        $stmt = $this->db->prepare("
                            INSERT INTO categories (user_id, name, color, icon) 
                            VALUES (?, ?, '#667eea', 'fas fa-folder')
                        ");
                        if ($stmt->execute([$user['id'], $bookmark['folder']])) {
                            $folderMap[$bookmark['folder']] = $this->db->lastInsertId();
                        }
                    }
                }
                $categoryId = $folderMap[$bookmark['folder']] ?? null;
            }
            
            // 插入书签
            try {
                // 生成favicon URL
                $parsedUrl = parse_url($bookmark['url']);
                $favicon = null;
                if (isset($parsedUrl['scheme']) && isset($parsedUrl['host'])) {
                    $favicon = $parsedUrl['scheme'] . '://' . $parsedUrl['host'] . '/favicon.ico';
                }
                
                $stmt = $this->db->prepare("
                    INSERT INTO bookmarks (user_id, category_id, name, url, description, favicon, created_at) 
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                ");
                
                $createdAt = $bookmark['created_at'] ?? date('Y-m-d H:i:s');
                
                if ($stmt->execute([
                    $user['id'],
                    $categoryId,
                    $bookmark['name'],
                    $bookmark['url'],
                    $bookmark['description'] ?? '',
                    $favicon,
                    $createdAt
                ])) {
                    $imported++;
                    $existingUrls[] = $bookmark['url']; // 添加到已存在列表
                } else {
                    $failed++;
                }
            } catch (Exception $e) {
                $failed++;
            }
        }
        
        sendSuccessResponse([
            'imported' => $imported,
            'skipped' => $skipped,
            'failed' => $failed,
            'total' => count($bookmarks)
        ], "导入完成：成功 {$imported} 个，跳过 {$skipped} 个，失败 {$failed} 个");
    }
    
    /**
     * 获取用户所有书签的URL
     */
    private function getUserBookmarkUrls($userId) {
        $stmt = $this->db->prepare("SELECT url FROM bookmarks WHERE user_id = ?");
        $stmt->execute([$userId]);
        $urls = [];
        while ($row = $stmt->fetch()) {
            $urls[] = $row['url'];
        }
        return $urls;
    }
    
    /**
     * 分析文件内容（快速预览）
     */
    private function analyzeFile() {
        $user = $this->requireAuth();
        
        if (!isset($_FILES['file'])) {
            sendErrorResponse('请选择要分析的文件');
        }
        
        $file = $_FILES['file'];
        $fileContent = file_get_contents($file['tmp_name']);
        $fileName = $file['name'];
        $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        
        $analysis = [
            'filename' => $fileName,
            'size' => $file['size'],
            'type' => $fileExt,
            'estimated_count' => 0,
            'preview' => []
        ];
        
        // 简单统计
        switch($fileExt) {
            case 'html':
            case 'htm':
                preg_match_all('/<a[^>]+href=/i', $fileContent, $matches);
                $analysis['estimated_count'] = count($matches[0]);
                break;
            case 'json':
                $data = json_decode($fileContent, true);
                if (isset($data['bookmarks'])) {
                    $analysis['estimated_count'] = count($data['bookmarks']);
                } elseif (is_array($data)) {
                    $analysis['estimated_count'] = count($data);
                }
                break;
            case 'csv':
                $lines = explode("\n", $fileContent);
                $analysis['estimated_count'] = max(0, count($lines) - 1);
                break;
        }
        
        sendSuccessResponse($analysis);
    }
}

// 处理请求
$api = new ImportAPI();
$api->handleRequest();

